﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NGinnBPM.Rules.TableDriven
{
    

    public class RuleScriptGenerator
    {
        public void GenerateScript(RulesetDef rs, TextWriter output)
        {
            output.WriteLine("RulesetName = '{0}'", rs.Name);
            output.WriteLine();
            foreach (RuleDef rd in rs.Rules)
            {
                output.WriteLine("rule '{0}':", rd.Id);
                StringBuilder sb = new StringBuilder();
                foreach (string cond in rd.Conditions)
                {
                    if (sb.Length > 0)
                        sb.Append(" and ");
                    sb.Append(string.Format(" ({0}) ", cond));
                }
                if (sb.Length == 0)
                    sb.Append("true");
                output.WriteLine("\tcondition:");
                output.WriteLine("\t\treturn {0}", sb.ToString());
                //output.WriteLine("\tend");
                output.WriteLine("\taction:");
                foreach (string act in rd.Actions)
                {
                    output.WriteLine("\t\t{0}", act);
                }
                //output.WriteLine("\tend");
                //output.WriteLine("end");
                output.WriteLine();
            }
        }

        public void GenerateScript(RulesetDef rs, string outFile)
        {
            using (StreamWriter sw = new StreamWriter(outFile, false, Encoding.UTF8))
            {
                GenerateScript(rs, sw);
            }
        }
    }
}
